import { Inject, Provide } from "@midwayjs/core";
import { BaseService, CoolCommException } from "@cool-midway/core";
import { ModuleType, ProviderProfileEntity } from "../entity/profile";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Equal, Repository } from "typeorm";
import { Context } from "@midwayjs/koa";
import { AddProviderProfileDTO, SaveMyProfileDTO } from "../dto/profile";
import { ProviderPartnerEntity } from "../entity/partner";
import { CapacityEntity } from "../../transport/entity/capacity";
import { TransportType } from "../../transport/entity/type";
import { ProviderTeamEntity } from "../entity/team";
import axios from 'axios';

@Provide()
export class ProviderProfileService extends BaseService {
    @InjectEntityModel(ProviderProfileEntity)
    providerProfileEntity: Repository<ProviderProfileEntity>

    @InjectEntityModel(ProviderPartnerEntity)
    partnerModel: Repository<ProviderPartnerEntity>

    @InjectEntityModel(CapacityEntity)
    capacityModel: Repository<CapacityEntity>

    @InjectEntityModel(ProviderTeamEntity)
    providerTeamEntity: Repository<ProviderTeamEntity>

    @Inject()
    ctx: Context



    // 司导端： 检查我是否已经填写了个人信息
    async checkMyProfile() {
        const providerId = this.ctx.provider.id as number;
        return this.providerProfileEntity.exists({
            where: { providerId: Equal(providerId) },
        });
    }

    // 司导端： 新增服务人员基础信息
    async add(dto: AddProviderProfileDTO) {
        const exist = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(dto.providerId) },
        });
        if (exist) {
            throw new CoolCommException('该服务人员已存在');
        }
        return await this.providerProfileEntity.save({
            providerId: dto.providerId,
            name: dto.name,
            gender: dto.gender,
            photo: dto.photo,
        });
    }

    //司导端： 保存我的资料
    async saveMyProfile(dto: SaveMyProfileDTO) {
        return this.providerProfileEntity.manager.transaction(async manager => {
            const exist = await manager.findOne(ProviderProfileEntity, { where: { providerId: Equal(this.ctx.provider.id) } });
            if (!exist) {
                const capacity = await manager.save(CapacityEntity, {
                    type: TransportType.PROVIDER,
                });
                const profile = await manager.save(ProviderProfileEntity, {
                    providerId: this.ctx.provider.id,
                    ...dto,
                    capacityId: capacity.id,

                });

                // 更新团队绑定的运力ID
                let team = await manager.findOne(ProviderTeamEntity, { where: { ownerProviderId: Equal(this.ctx.provider.id) } });
                if (!team) {
                    team = await manager.save(ProviderTeamEntity, {
                        ownerProviderId: this.ctx.provider.id,
                        name: dto.name + '团队',
                        introduction: dto.teamIntroduction,
                        isTenant: false,
                    });
                }

                await manager.update(CapacityEntity, { id: capacity.id }, { teamId: team.id });

                return profile;
            }
            return manager.save(ProviderProfileEntity, {
                ...exist,
                ...dto,
                phone: this.ctx.provider.phone,
                capacityId: exist.capacityId,

            });
        });
    }

    // 司导端： 获取我的资料
    async getProfile(providerId: number) {
        const profile = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(providerId) },
        });
        if (!profile) {
            throw new CoolCommException('您的资料不存在')
        }
        // 优先判断是否是团队所有者
        const ownerTeam = await this.providerTeamEntity.findOne({
            where: { ownerProviderId: Equal(providerId) },
        });
        if (ownerTeam) {
            return {
                ...profile,
                isTeamMaster: true,
                team: ownerTeam,
            }
        }
        // 非团队所有者：查询加入的团队（通过运力 teamId 反查团队）
        const myCapacity = await this.capacityModel.findOne({ where: { id: Equal(profile.capacityId) } });
        const joinedTeam = myCapacity?.teamId
            ? await this.providerTeamEntity.findOne({ where: { id: Equal(myCapacity.teamId) } })
            : null;
        return {
            ...profile,
            isTeamMaster: false,
            team: joinedTeam,
        }
    }

    // 司导端： 根据团队ID查询所属服务人员信息
    async getChildProfilesByTeamId(teamId: number) {
        // return await this.providerProfileEntity.find({
        //     where: { teamId: Equal(teamId) },
        // });
        // 1. 查询团队绑定的运力ID
        const capacity = await this.capacityModel.findOne({
            where: {
                teamId: Equal(teamId), type: TransportType.PROVIDER
            }
        });
        if (!capacity) {
            return [];
        }
        // 2. 查询运力绑定的服务人员信息
        // return await this.providerProfileEntity.find({ where: { capacityId: Equal(capacity.id) } });
    }


    // 司导端：根据团队ID查询合作服务人员信息
    async getPartnerProfilesByTeamId(teamId: number) {

    }

    /**
     * 获取服务人员常驻地的天气和时间
     * @param providerId 
     */
    async getWeatherAndLocalTime(providerId: number) {
        const profile = await this.providerProfileEntity.findOne({ where: { providerId } });
        if (!profile || !profile.residence) {
            throw new CoolCommException('未找到该服务人员的常驻地信息');
        }
        const city = profile.residence;
        try {
            // 使用 wttr.in 获取天气和时间
            // format=j1 返回 JSON
            // lang=zh 支持中文
            const url = `https://wttr.in/${encodeURIComponent(city)}?format=j1&lang=zh`;
            const response = await axios.get(url, { timeout: 5000 });
            const data = response.data;

            if (!data || !data.current_condition || !data.current_condition[0]) {
                return { city, weather: '未知', temp: '', time: '' };
            }

            const current = data.current_condition[0];
            // 优先使用中文描述
            const weather = current.lang_zh ? current.lang_zh[0].value : (current.weatherDesc ? current.weatherDesc[0].value : '');
            const temp = current.temp_C;
            // wttr.in 返回的是观测时间，通常接近当地时间
            const localTime = current.localObsDateTime;

            return {
                city,
                weather,
                temp,
                localTime
            };
        } catch (e) {
            // 记录日志或忽略
            console.error('获取天气失败', e.message);
            return { city, weather: '获取失败', temp: '', time: '' };
        }
    }

}